package com.action;

import cn.hutool.core.lang.Assert;
import com.bean.ResponseBean;
import com.deepoove.poi.XWPFTemplate;
import com.util.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class UploadAction {

    @Value("${upload.tmp.dir}")
    private String tmp;

    @Value("${upload.dir}")
    private String upload ;

    @Value("${upload.excel}")
    public String excel;
    @Value("${host}")
    private String yuming;

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate rt ;

//    @Autowired
//    private HetongGuanliService hetongGuanliService;
//    @Autowired
//    private ChukujiluService chukujiluService;
//    @Autowired
//    private HeTongService heTongService;

    @PostMapping("/uploadImg")
    @CrossOrigin("*")
    public ResponseBean uploadImg(MultipartFile  file) throws IllegalStateException, IOException
    {
        //目的地1
        File uploadFile = new File(upload);
        if (uploadFile.exists()==false){
            uploadFile.mkdirs();
        }

        File uploadFile2 = new File(upload+"images/muban");
        if (uploadFile2.exists()==false){
            uploadFile2.mkdirs();
        }
        //目的地2  类别图片
        /*File typeFile = new File(upload+"type");
        if (typeFile.exists()==false){
            typeFile.mkdirs();
        }
        //目的地3  自提点图片
        File zitidianLogo = new File(upload+"images/zitidianLogo");
        if (zitidianLogo.exists()==false){
            zitidianLogo.mkdirs();
        }
        //目的地4  轮播图图片
        File lunbotu = new File(upload+"lunbotu");
        if (lunbotu.exists()==false){
            lunbotu.mkdirs();
        }
        //目的地5  退换货图片
        File refund = new File(upload+"tuiHuanHuoImages");
        if (refund.exists()==false){
            refund.mkdirs();
        }
        //目的地6  用户头像
        File userIcon = new File(upload+"userIcon");
        if (userIcon.exists()==false){
            userIcon.mkdirs();
        }
        //目的地7  店铺图片
        File merchant = new File(upload+"merchant");
        if (merchant.exists()==false){
            merchant.mkdirs();
        }
        //目的地8  评价图片
        File appraise = new File(upload+"appraise");
        if (appraise.exists()==false){
            appraise.mkdirs();
        }
        //目的地9  骑手图片
        File rider = new File(upload+"rider");
        if (rider.exists()==false){
            rider.mkdirs();
        }
        */
        //目的地
        File tmpFile = new File(tmp);
        if (tmpFile.exists()==false){
            tmpFile.mkdirs();
        }

        //得到旧的文件名
        String oldFileName = file.getOriginalFilename();
        //得到原来的后辍名
        int index = oldFileName.lastIndexOf('.');
        int index2=-10;
        if(index<0)
            index2=file.getContentType().lastIndexOf('/');
        String extName="";
        if(index>-1)
            extName = oldFileName.substring(index);
        if(index2>-1)
            extName="."+file.getContentType().substring(index2+1);
        //根据系统时间拼一个当前新的文件名
        String newFileName = System.currentTimeMillis()+extName;
        //目的地
        File descFile = new File(tmp, newFileName);
        file.transferTo(descFile);

        return new ResponseBean(0, "上传成功", newFileName);
    }

    @RequestMapping("/upload")
    public ResponseBean upload(MultipartFile file) throws IOException {

        //System.out.println("传过来的文件："+file);
        //得到原来的文件名  xxxx.jpg
        if(file == null){
            return new ResponseBean(0,0,"");
        }
        String oldFileName = file.getOriginalFilename();
        //得到一个最后一个.的位置
        int index = oldFileName.lastIndexOf('.');
        //得到后辍名
        String extName = oldFileName.substring(index);
        //新的文件名
        String newFileName = System.currentTimeMillis()+extName;
        //传到tmp目录
        File descFile = new File(tmp, newFileName);
        file.transferTo(descFile);

        //System.out.println("新图片："+newFileName);
        return new ResponseBean(0,0,newFileName);
    }

    @RequestMapping(value="/uploadImage")
    @ResponseBody
    public Object uploadImage(MultipartFile file) {
        String filename = file.getOriginalFilename();
        boolean boole = true;
        String newFileName = "";
        if(file == null) {
            return ResponseBean.error("0") ;
        }
        try{
            String oldFileName = file.getOriginalFilename();
            //得到一个最后一个.的位置
            int index = oldFileName.lastIndexOf('.');
            //得到后辍名
            String extName = oldFileName.substring(index);
            //新的文件名
            newFileName = System.currentTimeMillis() + extName;
            file.transferTo(new File(upload + newFileName));
        }catch (Exception e){
            System.out.println("图片保存异常");
            boole = false;
        }
        if (boole) {
            Map<String,Object> map = new HashMap<String,Object>();
            Map<String,Object> map2 = new HashMap<String,Object>();
            map.put("code", 0);	//0表示上传成功
            map.put("msg","上传成功"); //提示消息
            map2.put("src", yuming+"upload/" + newFileName);
            map2.put("title", newFileName);
            map.put("data", map2);
            return map;
        } else {
            return new ResponseBean(1,1,newFileName);
        }
    }

    @RequestMapping("/upload_bg")
    public ResponseBean uploadBg(MultipartFile file) throws IOException {

        //System.out.println("传过来的文件："+file);
        //得到原来的文件名  xxxx.jpg
        String oldFileName = file.getOriginalFilename();
        //得到一个最后一个.的位置
        int index = oldFileName.lastIndexOf('.');
        //得到后辍名
        String extName = oldFileName.substring(index);
        //新的文件名
        String newFileName = System.currentTimeMillis()+extName;
        //传到tmp目录
        File descFile = new File(upload, newFileName);
        file.transferTo(descFile);

        rt.boundValueOps("wuye:gongpai:bg").set(newFileName);

        //System.out.println("新图片："+newFileName);
        return new ResponseBean(200,0,newFileName);
    }

    /**
     *上传Excel
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/fileUpload")
    @ResponseBody
    public ResponseBean fileUpload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return new ResponseBean(1,0,"上传失败，请选择文件");
        }

        File poi = new File(excel);
        if(poi.exists()==false){
            poi.mkdirs();
        }

        String fileName = file.getOriginalFilename();
        //得到一个最后一个.的位置
        int index = fileName.lastIndexOf('.');
        //得到后辍名
        String extName = fileName.substring(index);
        //新的文件名
        String newFileName = System.currentTimeMillis()+extName;

        String filePath = excel;
        File dest = new File(filePath + newFileName);
//        System.out.println("文件上传后地址："+dest);

        List<String> list = ExcelUtils.excelToShopIdList(file.getInputStream());
//        System.out.println("商品列表："+list);
//        System.out.println("商品列表长度："+list.size());

        int chang = list.size();
        String x = list.get(chang-2);
        int y = x.indexOf("：");
        String shenbaoren = x.substring(y+1,x.length());
        String shenbaoID = list.get(chang-1);
//        System.out.println("申报人："+shenbaoren);
//        System.out.println("申报ID："+list.get(chang-1));

//        List<Huowu> huowus = new ArrayList<Huowu>();
//        for (int i = 0; i < list.size()/7; i++) {
//            Huowu huowu = new Huowu();
//            huowu.setMark(list.get(7*i+0));
//            huowu.setPhone(list.get(7*i+1));
//            huowu.setKehu_name(list.get(7*i+2));
//            huowu.setKehu_status(Integer.valueOf(list.get(7*i+3)));
//            huowu.setZhengjian_name(list.get(7*i+4));
//            huowu.setZhengjian_status(Integer.valueOf(list.get(7*i+5)));
//            huowu.setZhengjian_number(list.get(7*i+6));
//            huowu.setJingyin_xuke(shenbaoID);
//            huowus.add(huowu);
//        }

//        list.add(newFileName);
        try {
            file.transferTo(dest);
            return new ResponseBean(0,1,newFileName+"?"+shenbaoren+"&"+shenbaoID,"huowus");
        } catch (IOException e) {

        }
        return new ResponseBean(0,0,newFileName+"?"+shenbaoren+"&"+shenbaoID,"huowus");
    }

    @RequestMapping("/xiazaiHeTong")
    @ResponseBody
    public void downStudentSolvedSubject(@RequestParam(value="id",defaultValue ="")String id,
                                         HttpServletResponse response){


    }

    /**
     * 根据模板填充内容生成word
     * 调用方法参考下面的main方法，详细文档参考官方文档
     * Poi-tl模板引擎官方文档：http://deepoove.com/poi-tl/
     *
     * @param templatePath word模板文件路径
     * @param fileDir      生成的文件存放地址
     * @param fileName     生成的文件名,不带格式。假如要生成abc.docx，则fileName传入abc即可
     * @param paramMap     替换的参数集合
     * @return 生成word成功返回生成的文件的路径，失败返回空字符串
     */
    public static String createWord(String templatePath, String fileDir, String fileName, Map<String, Object> paramMap) {
        Assert.notNull(templatePath, "word模板文件路径不能为空");
        Assert.notNull(fileDir, "生成的文件存放地址不能为空");
        Assert.notNull(fileName, "生成的文件名不能为空");

        // 生成的word格式
        //String formatSuffix = ".docx";
        // 拼接后的文件名
        //fileName = fileName + formatSuffix;

        // 生成的文件的存放路径
        if (!fileDir.endsWith("/")) {
            fileDir = fileDir + File.separator;
        }

        File dir = new File(fileDir);
        if (!dir.exists()) {
            log.info("生成word数据时存储文件目录{}不存在,为您创建文件夹!", fileDir);
            dir.mkdirs();
        }

        String filePath = fileDir + fileName;
        //System.out.println("文件路径：" + filePath);
        // 读取模板templatePath并将paramMap的内容填充进模板，即编辑模板+渲染数据
        XWPFTemplate template = XWPFTemplate.compile(templatePath).render(paramMap);
        try {
            // 将填充之后的模板写入filePath
            template.writeToFile(filePath);
            template.close();
        } catch (Exception e) {
            log.error("生成word异常", e);
            e.printStackTrace();
            return "";
        }
        return filePath;
    }
    /**
     * 获取结束时间与开始时间相差多少个月份
     * @param start
     * @param end
     * @return
     */
    public int getDifference(String start, String end) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String str1 = start.substring(0, 7);
        String str2 = end.substring(0, 7);
        Calendar bef = Calendar.getInstance();
        Calendar aft = Calendar.getInstance();
        try {
            bef.setTime(sdf.parse(str1));
            aft.setTime(sdf.parse(str2));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
        int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12;
        System.out.println(Math.abs(month + result));
        return Math.abs(month + result);

    }

}
